<script setup>
import { ref, onMounted, watch } from "vue";
import { ElMessage, ElMessageBox } from "element-plus"; //引入element-plus的消息提示组件
import { queryAllApi as queryAllEmpApi } from "@/api/emp";

import {
  queryPageApi,
  addApi,
  queryInfoApi,
  updateApi,
  deleteApi,
} from "@/api/clazz";

//声明列表展示数据
const clazzList = ref([]);

//表单输入数据
const searchClazz = ref({ begin: "", end: "", date: [], name: "" });
//钩子函数
onMounted(() => {
  queryPage();
  queryAll();
});
//所有的员工数据
let emps = ref([]);
//学科列表数据
const subjects = ref([
  { name: "Java", value: 1 },
  { name: "前端", value: 2 },
  { name: "大数据", value: 3 },
  { name: "Python", value: 4 },
  { name: "Go", value: 5 },
  { name: "嵌入式", value: 6 },
]);
//加载所有的员工数据
const queryAllEmp = async () => {
  let result = await queryAllEmpApi();
  if (result.code) {
    emps.value = result.data;
  }
};
//动态加载数据-查询班级
const queryAll = async () => {
  const result = await queryAllEmp();
  clazzList.value = result.data;
};
//分页组件
const pagination = ref({ currentPage: 1, pageSize: 5, total: 0 });
//每页展示记录数发生变化时触发参数是每页展示记录数
const handleSizeChange = (pageSize) => {
  pagination.value.pageSize = pageSize;
  queryPage();
};
//当前页码发生变化时触发参数是当前页码
const handleCurrentChange = (page) => {
  pagination.value.currentPage = page;
  queryPage();
};
//分页条件查询
const queryPage = async () => {
  const result = await queryPageApi(
    searchClazz.value.begin,
    searchClazz.value.end,
    searchClazz.value.name,
    pagination.value.currentPage,
    pagination.value.pageSize
  );
  if (result.code) {
    clazzList.value = result.data.rows;
    pagination.value.total = result.data.total;
  }
};

//清空搜索栏
const clear = () => {
  searchClazz.value = { begin: "", end: "", date: [], name: "" };
  queryPage();
};

//监听searchEmp的date属性变化
watch(
  () => searchClazz.value.date,
  (newVal, oldVal) => {
    if (newVal.length > 0) {
      searchClazz.value.begin = newVal[0];
      searchClazz.value.end = newVal[1];
    } else {
      searchClazz.value.begin = "";
      searchClazz.value.end = "";
    }
  }
);

//新增/编辑班级
//表单引用
const clazzFormRef = ref(null);
let labelWidth = ref(80) //form表单label的宽度
//表单校验
const rules = ref({
  name: [
    { required: true, message: '班级名称为必填项', trigger: 'blur' },
    { min: 4, max: 30, message: '用户名长度为4-30个字', trigger: 'blur' }
  ],
  room: [
    { min: 1, max: 20, message: '班级教室长度为1-20个字', trigger: 'blur' }
  ],
  beginDate: [{ required: true, message: '开课时间为必填项', trigger: 'change' }],
  endDate: [{ required: true, message: '结课时间为必填项', trigger: 'change' }],
  subject: [{ required: true, message: '学科为必填项', trigger: 'change' }]
})
//通过表单引用重置表单
const resetForm = () => {
  //相比于清空表单，resetFields()方法会将表单的校验状态也一并清空
  clazzFormRef.value.resetFields()
}
//表单数据
const clazz = ref({
  id: "",
  name: "",
  room: "",
  beginDate: "",
  endDate: "",
  subject: "",
  masterId: "",
});
//清空表单
const clearClazz = () => {
  clazz.value = {
    id: "",
    name: "",
    room: "",
    beginDate: "",
    endDate: "",
    subject: "",
    masterId: "",
  };
};
//新增/编辑班级
let dialogFormVisible = ref(false); //控制新增/修改的对话框的显示与隐藏
let formTitle = ref(""); //表单的标题
//新增班级
const addClazz = async () => {
  formTitle.value = "新增班级";
  dialogFormVisible.value = true;
  //清空表单
  resetForm()
};
//编辑班级数据回显
const editClazz = async (id) => {
  clearClazz();//编辑
  dialogFormVisible.value = true;
  const result = await queryInfoApi(id);
  if (result.code) {
    clazz.value = result.data;
  }
};
//保存班级信息 
const save = async () => {
  await clazzFormRef.value.validate(async (valid) => {
    if (!valid) return;
    let result = null;
    if (clazz.value.id) {
      result = await updateApi(clazz.value);
    } else {
      result = await addApi(clazz.value);
    }
    if (result.code) {
      ElMessage.success("操作成功");
      dialogFormVisible.value = false;
      resetForm();
      queryPage();
    } else {
      ElMessage.error(result.msg);
    }
  });
};

//删除班级
const deleteClazz = async (id) => {
  ElMessageBox.confirm("是否删除该班级", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const result = await deleteApi(id);
    if (result.code) {
      ElMessage.success("删除成功");
      queryPage();
    } else {
      ElMessage.error(result.msg);
    }
  }).catch(() => {
    ElMessage.info('取消删除')
  })
};

//监听searchEmp的date属性
watch(
  () => searchClazz.value.date,
  (newVal, oldVal) => {
    if (newVal.length > 0) {
      searchClazz.value.begin = newVal[0];
      searchClazz.value.end = newVal[1];
    } else {
      searchClazz.value.begin = "";
      searchClazz.value.end = "";
    }
  }
);
</script>

<template>

  <div>
    <div id="title">班级管理</div>
    <br />
  </div>

  <!-- 条件搜索表单 inline作用是将表单元素放在同一行 -->
  <div class="container">
    <el-form :model="searchClazz" :inline="true" size="large" label-width="80px">
      <el-form-item label="班级名称">
        <el-input v-model="searchClazz.name" placeholder="请输入班级名称"></el-input>
      </el-form-item>
      <el-form-item label="结课时间">
        <el-date-picker v-model="searchClazz.date" type="daterange" range-separator="至" start-placeholder="开始日期"
          end-placeholder="结束日期" value-format="YYYY-MM-DD"></el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="queryPage">查询</el-button>
        <el-button @click="clear">清空</el-button>
      </el-form-item>
    </el-form>
  </div>

  <!-- 按钮靠页面左侧显示 -->
  <div class="container">
    <el-button type="success" @click="addClazz" size="large">新增班级</el-button>
    <br />
  </div>
  <!-- 展示班级列表:序号 班级名称 班级教室 班主任 开课时间 结课时间 状态 最后操作时间 操作(编辑 删除) -->
  <div class="container">
    <el-table :data="clazzList" border style="width: 100%">
      <el-table-column type="index" label="序号" width="55" align="center" />
      <el-table-column prop="name" label="班级名称" width="200" align="center" />
      <el-table-column prop="room" label="班级教室" width="100" align="center" />
      <el-table-column prop="masterName" label="班主任" width="100" align="center" />
      <el-table-column prop="beginDate" label="开课时间" width="150" align="center" />
      <el-table-column prop="endDate" label="结课时间" width="150" align="center" />
      <el-table-column prop="status" label="状态" width="200" align="center" />
      <el-table-column prop="updateTime" label="最后操作时间" width="130" align="center" />
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button type="primary" size="mini" @click="editClazz(scope.row.id)">编辑</el-button>
          <el-button type="danger" size="mini" @click="deleteClazz(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>

  <!-- 分页组件 -->
  <div class="container">
    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
      :current-page="pagination.currentPage" :page-sizes="[5, 10, 20, 30, 40]" :page-size="pagination.pageSize"
      layout="total, sizes, prev, pager, next, jumper" :total="pagination.total"></el-pagination>
  </div>

  <!-- 新增/编辑班级对话框 -->
  <el-dialog v-model="dialogFormVisible" :title="formTitle" width="35%">
    <el-form :model="clazz" ref="clazzFormRef" :rules="rules">
      <el-form-item label="班级名称" prop="name" :label-width="labelWidth">
        <el-input v-model="clazz.name" placeholder="请输入班级名称" />
      </el-form-item>
      <el-form-item label="班级教室" prop="room" :label-width="labelWidth">
        <el-input v-model="clazz.room" placeholder="请输入班级教室" />
      </el-form-item>
      <el-form-item label="开课时间" prop="beginDate" :label-width="labelWidth">
        <el-date-picker v-model="clazz.beginDate" type="date" placeholder="请选择开课时间" value-format="YYYY-MM-DD"
          style="width: 100%"></el-date-picker>
      </el-form-item>
      <el-form-item label="结课时间" prop="endDate" :label-width="labelWidth">
        <el-date-picker v-model="clazz.endDate" type="date" placeholder="请选择结课时间" value-format="YYYY-MM-DD"
          style="width: 100%"></el-date-picker>
      </el-form-item>
      <el-form-item label="班主任" :label-width="labelWidth">
        <el-select v-model="clazz.masterId" placeholder="请选择班主任" style="width: 100%">
          <el-option v-for="emp in emps" :key="emp.id" :label="emp.name" :value="emp.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="学科" prop="subject" :label-width="labelWidth">
        <el-select v-model="clazz.subject" placeholder="请选择学科" style="width: 100%">
          <el-option v-for="sub in subjects" :key="sub.value" :label="sub.name" :value="sub.value"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="
          dialogFormVisible = false;
        resetForm(clazzFormRef);
        ">取消</el-button>
        <el-button type="primary" @click="save()">保存</el-button>
      </span>
    </template></el-dialog>
</template>

<style scoped>
.container {
  margin: 10px 0;
}

#title {
  font-size: 20px;
  font-weight: 600;
}
</style>